extends Node
class_name GameEvaluation # 局势评估

var redWinRate: float = 0
var blackWinRate: float = 0

signal sourceChange(side: BoardCommon.TURN) ## 得分变化信号

var redScore: int: ## 红方得分
	set(value):
		redScore = + value
var blackScore: int: ## 黑方得分
	set(value):
		blackScore = + value
var boardEvaluateTables: Resource = preload("res://Resource/BoardEvaluate.json") ## 棋盘评估表
var pieceEvaluateTables: Resource = preload("res://Resource/PieceEvaluete.json") ## 棋子评估表
## 初始化
func _ready() -> void:
	sourceChange.connect(_on_calculateRate)
	redScore = 0
	blackScore = 0
	
## 胜率计算
func _on_calculateRate(side: BoardCommon.TURN) -> void:
	if ((blackScore + redScore) == 0): return
	match side:
		BoardCommon.TURN.RED:
			GlobalSignals.label_update_change_score_signal.emit(BoardCommon.TURN.RED,redScore)
			redWinRate = 1.0 * redScore / (blackScore + redScore) ## 计算红方胜率
		BoardCommon.TURN.BLACK:
			GlobalSignals.label_update_change_score_signal.emit(BoardCommon.TURN.BLACK,blackScore)
			blackWinRate = 1.0 * blackScore / (blackScore + redScore) ## 计算黑方胜率
	print("红方胜率：", redWinRate, "黑方胜率：", blackWinRate)
	print("红方得分：", redScore, "黑方得分：", blackScore)


## 移动得分
func move_score(side: BoardCommon.TURN, type: BoardCommon.TYPE, start_pos: Vector2i, end_pos: Vector2i) -> int:
	var score: int = 0 # 计算得分
	var start_pos_x: int = int(start_pos.x)
	var start_pos_y: int = int(start_pos.y)
	var end_pos_x: int = int(end_pos.x)
	var end_pos_y: int = int(end_pos.y)
	var prePosScore: int = boardEvaluateTables.data[BoardCommon.TURN_NAMES[side]][BoardCommon.TYPE_NAMES[type]][start_pos_y][start_pos_x] # 计算当前位置得分
	var postPosScore: int = boardEvaluateTables.data[BoardCommon.TURN_NAMES[side]][BoardCommon.TYPE_NAMES[type]][end_pos_y][end_pos_x] # 计算下一步的得分
	
	match side:
		BoardCommon.TURN.RED:
			score += postPosScore - prePosScore # 如果是红方移动，计算位置提升得分
		BoardCommon.TURN.BLACK:
			score += postPosScore - prePosScore # 如果是蓝方移动，计算位置提升得分
	return score
## 棋子死亡得分
func _on_calculate_piece_died(side: BoardCommon.TURN, type: BoardCommon.TYPE) -> void:
	match side:
		BoardCommon.TURN.RED:
			blackScore+=pieceEvaluateTables.data[BoardCommon.TYPE_NAMES[type]]
			_on_calculateRate(BoardCommon.TURN.BLACK)
		BoardCommon.TURN.BLACK:
			redScore+=pieceEvaluateTables.data[BoardCommon.TYPE_NAMES[type]]
			_on_calculateRate(BoardCommon.TURN.RED)

## 处理移动得分
func handle_move_score(side: BoardCommon.TURN, type: BoardCommon.TYPE, start_pos: Vector2i, end_pos: Vector2i) -> void:
	var score:int = move_score(side, type, start_pos, end_pos)
	match side:
		BoardCommon.TURN.RED: redScore += score # 如果是红方移动，计算位置提升得分
		BoardCommon.TURN.BLACK: blackScore += score # 如果是蓝方移动，计算位置提升得分
	_on_calculateRate(side)
